package com.woniu.demo.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * created by woniu201
 * created in 2018/6/21
 */
@Slf4j
@Component
@WebFilter( urlPatterns = {"/test1", "/test2", "/test3", "/test4"})
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("过滤器初始化方法");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //application:www-urlencode 对应测试Controller为/test1   test2
        //注意事项：
        //1.可以直接用getparameter接收
        //2.controller接收直接用对象接收
//        System.out.println(req.getParameter("token"));
//        filterChain.doFilter(req, resp);


        //content-type:application-json
        //注意事项：
        //1.直接getparameter无法读取到参数
        //2.controller对象接收时要加@RequestBody注解
        if ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod())){
            String path = req.getQueryString();
            if (path == null) {
                Map<String, String> headerMap = new HashMap<String, String>();
                Enumeration headerNames =  req.getHeaderNames();
                while (headerNames.hasMoreElements()) {//循环遍历Header中的参数，把遍历出来的参数放入Map中
                    String key = (String) headerNames.nextElement();
                    String value = req.getHeader(key);
                    headerMap.put(key, value);
                }
                System.out.println("请求头信息：\n" + headerMap.toString());
            }
            String url = req.getRequestURI();
            String repalceUrl = url.replaceAll("/", "");
            if (null != repalceUrl) {
                repalceUrl = repalceUrl.trim();
            } else {
                return;
            }
            System.out.println("请求URL：" + url);

            //获取请求参数
            RequestWrapper requestWrapper = null;
            ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
            StringBuilder sb = null;
            if (servletRequest instanceof HttpServletRequest) {
                requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
                try {
                    BufferedReader bufferedReader = requestWrapper.getReader();
                    String line;
                    sb = new StringBuilder();
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            System.out.println(sb.toString());

//            filterChain.doFilter(requestWrapper, responseWrapper);
            filterChain.doFilter(requestWrapper, servletResponse);


//        responseWrapper.setHeader("Content-Type","application/json");
//            servletResponse.setContentLength(-1);//解决可能在运行的过程中页面只输出一部分
//            servletResponse.setCharacterEncoding("UTF-8");
//            PrintWriter out = servletResponse.getWriter();
//            out.write(new String(responseWrapper.getResponseData()));
//            out.flush();
//            out.close();
        }else{
            filterChain.doFilter(req, resp);
        }



    }

    @Override
    public void destroy() {
        log.info("过滤器销毁方法");
    }
}
